package com.tanker.service.car;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import net.sf.json.JSONObject;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tanker.model.Oauth2Token;
import com.tanker.model.WxMemberInfo;
import com.tanker.util.wxx.WxHttpUtil;

/**
 * @author xqxue
 * @time 2017年11月17日 下午3:30:37
 */
@Service
public class UserInfoService {

	private final static Logger logger = LoggerFactory.getLogger(UserInfoService.class);
	
	public final static String Oauth2_Token_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	
	public final static String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	public final static String USER_INFO_URL2 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";	
	

			
	/**
	 * 通过code换取网页授权access_token
	 * @param appId   公众账号的唯一标识
	 * @param appSecret 公众账号的密钥
	 * @param code
	 * @return Aouth2Token
	 */
	public Oauth2Token getOauth2AccessToken(String appId,
			String appSecret, String code) {
		logger.info("通过code获取access_token, code={}", code);

		String requestUrl = Oauth2_Token_URL.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);

		Oauth2Token token = null;
		JSONObject jsonObject = WxHttpUtil.httpRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
			try {
				token = new Oauth2Token();
				token.setAccessToken(jsonObject.getString("access_token"));
				token.setExpiresIn(jsonObject.getInt("expires_in"));
				token.setRefreshToken(jsonObject.getString("refresh_token"));
				token.setOpenId(jsonObject.getString("openid"));
				token.setScope(jsonObject.getString("scope"));
				
				if(StringUtils.isNotBlank(token.getOpenId()) && StringUtils.isNotBlank(token.getAccessToken()))
					this.getUserInfo(token.getAccessToken(), token.getOpenId());
			} catch (Exception e) {
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				logger.error("通过code换取网页授权access_token errcode:{} errmsg:{}",
						errorCode, errorMsg);
			}
		}
		return token;
	}

	/**
	 * 通过网页授权获取用户信息
	 * @param accessToken  网页授权接口调用凭证
	 * @param openId  用户标识
	 * @return UserInfo
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	public WxMemberInfo getUserInfo(String accessToken, String openId) {
		logger.info("获取用户信息accessToken={}, openId={}", accessToken, openId);

		String requestUrl = USER_INFO_URL2.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);

		// 通过网页授权获取用户信息
		WxMemberInfo userInfo = null;
		JSONObject jsonObject = WxHttpUtil.httpRequest(requestUrl, "GET", null);
		if (null != jsonObject) {
			if(jsonObject.toString().indexOf("nickname")==-1)
				return null;
			try {
				userInfo = new WxMemberInfo();
				userInfo.setOpenid(jsonObject.getString("openid"));
				//if(jsonObject.getString("unionid")!=null)
					//userInfo.setUnionId(jsonObject.getString("unionId"));
				String nickname = jsonObject.getString("nickname");
				//System.out.println("nickname=" +  nickname);
				nickname = Base64.encodeBase64String(nickname.getBytes("utf-8"));
				userInfo.setNickname(nickname);
				userInfo.setSex(jsonObject.getInt("sex"));// 性别（1是男性，2是女性，0是未知）
				userInfo.setCountry(jsonObject.getString("country"));
				userInfo.setProvince(jsonObject.getString("province"));
				userInfo.setCity(jsonObject.getString("city"));
				userInfo.setHeadimgurl(jsonObject.getString("headimgurl"));// 用户头像
				/*userInfo.setPrivilege(jsonObject.getJSONArray("privilege").toString());
				userInfo.setPrivilegeList(JSONArray.toList(
						jsonObject.getJSONArray("privilege"), List.class)); // 用户特权信息
*/				
			} catch (Exception e) {
				e.printStackTrace();
				userInfo = null;
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				logger.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode,
						errorMsg);
			}
		}
		return userInfo;
	}

	public static void testCode() {
		// String url =
		// "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		JSONObject jsonObject = WxHttpUtil.httpRequest(url, "GET", null);
		System.out.println(jsonObject);
	}

	public static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String urlDecodeUTF8(String source) {
		String result = source;
		try {
			result = URLDecoder.decode(source);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static void main(String args[]) {
		 System.out.println(urlEncodeUTF8("http://ga6gmhy.hk1.mofasuidao.cn/wx/callBack"));
		//testCode();
	}
}
